/*
 * 
 */
package com.media.module.activity;

import java.io.File;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import com.droid.utils.BitmapHelper;
import com.droid.utils.Fileutils;
import com.droid.utils.ProgressDialogHelper;
import com.droid.utils.ProgressDialogHelper.ProgressCallBack;
import com.media.module.interfaces.AudioStater;
import com.media.module.model.OutputFormatMode;
import com.media.module.utils.ActivityStyle;
import com.media.module.utils.CameraUtils;
import com.media.module.utils.DimenValues;
import com.media.module.utils.MResource;
import com.media.module.utils.MediaConst;
import com.media.module.utils.UIGlobalDef;
import com.media.module.view.FooterView;
import com.media.module.view.HeaderView;
import com.media.module.widget.RoundProgressBar;
import com.media.module.widget.WaveformView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AudioWavesActivity extends Activity implements OnClickListener, AudioStater {
	private final String TAG = "AudioWavesActivity";
	private static Context mContext;
	
	private ImageView mivCancel;
	private ImageView mivOk;
	private ImageView mivStart;
	private ImageView mivPause;
	private ImageView mivResume;
	private ImageView mivStop;
	private TextView mtvTime;
	private ImageView mivPreviewSound;
	private RoundProgressBar mrprbTime;
	
	private ViewGroup mvContent;
	//不同的波纹形状
//	private Visualizer mVisualizer;
	private WaveformView mWaveformView;
	
	private float mfBaseDimen;
	private int mintScreenWidth;
	private int mintScreenHeight;
	private int mNavigationBarHeight;
	private int mStatusBarHeight;
	    
	// 录像时间最大值
	private long mMaxTime;
	private String mstrSaveAudioDirPath;
	private OutputFormatMode mFormatMode;
	// 当前时刻
	private long mThisTimes;
	// 记录时间
	private long mRecorderTime;
	// 定时器
	private Timer mTimer;
	// 任务
	private TimerTask mTask;
	private boolean misStart = true;
	
	private final int INT_UPDATE_TAKE_TIME = 0x0001;
	private final int INT_STOP_UPDATE_VIEW = 0x0002;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			
			case INT_UPDATE_TAKE_TIME:
				if(mMaxTime == 0){ 
					mtvTime.setVisibility(View.VISIBLE);
					mtvTime.setText(CameraUtils.thisTime(mRecorderTime));
					mrprbTime.setProgress(0);
					mThisTimes = Calendar.getInstance().getTimeInMillis();
					break;
				}
				if (mRecorderTime <= mMaxTime) {
					mtvTime.setVisibility(View.VISIBLE);
					mtvTime.setText(CameraUtils.thisTime(mRecorderTime));
					int lintprogress = (int) Math.ceil((mRecorderTime) / (mMaxTime * 1.0) * 100);
					if (lintprogress > 0) {
						mrprbTime.setProgress(lintprogress);
					}
					mThisTimes = Calendar.getInstance().getTimeInMillis();
				} else {
					mivStop.performClick();

				}
				break;
			case INT_STOP_UPDATE_VIEW:
				mrprbTime.setProgress(0);
				String fPath = mWaveformView.getFilePath();
				if(fPath != null && fPath.isEmpty()){
					MediaScannerConnection.scanFile(mContext, new String[] {fPath }, null, null);
				}
				mivPreviewSound.setImageBitmap(BitmapHelper.drawableToBitmap(MResource.getDrawableFromAssets(mContext, "img_audio_background.png")));
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		initScreenParams();
		setContentView(getContentCameraView(getApplicationContext()), ActivityStyle.getContentCaneraLayoutParams());
		expandParams(getIntent().getBundleExtra(MediaConst.BUNDLE_DATA));
	}
	
	 /**
     * 屏幕参数
     */
    private void initScreenParams() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        mintScreenWidth = displayMetrics.widthPixels;
        mintScreenHeight = displayMetrics.heightPixels;
        mfBaseDimen =  MResource.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DimenValues.BASE_VALUE, displayMetrics);
        mNavigationBarHeight = (int) mfBaseDimen;
        mStatusBarHeight = (int) (mfBaseDimen * 1.2);
    }

    private void expandParams(Bundle params) {
        if (params == null) return;
        if(params.containsKey(MediaConst.OUTPUT_AUDIO_PATH)){
        	mstrSaveAudioDirPath = params.getString(MediaConst.OUTPUT_AUDIO_PATH) + File.separator;
        	Fileutils.createDir(mstrSaveAudioDirPath);
        }
        if(params.containsKey(MediaConst.MEDIA_RECORD_MAX_TIME)){
        	mMaxTime = params.getInt(MediaConst.MEDIA_RECORD_MAX_TIME) * 1000l;
        }
        if(params.containsKey(MediaConst.OUTPUT_AUDIO_FORMAT)){
        	mFormatMode = (OutputFormatMode) params.getSerializable(MediaConst.OUTPUT_AUDIO_FORMAT);
        }
    }
    
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case UIGlobalDef.VIEW_ID.CANCEL:
			mWaveformView.stop();
			finish();
			break;
		case UIGlobalDef.VIEW_ID.OK:
			Intent intent = getIntent();
			intent.setData(Uri.fromFile(new File(mWaveformView.getFilePath())));
			setResult(Activity.RESULT_OK, intent);
			finish();
			break;
		case UIGlobalDef.VIEW_ID.RECORD_MEDIA_START:
			setControlVisible(View.GONE, View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, View.VISIBLE,
					View.GONE);
			misStart = true;
			mWaveformView.startRecording(mstrSaveAudioDirPath, mFormatMode, misStart);
			break;
		case UIGlobalDef.VIEW_ID.RECORD_MEDIA_PAUSE:
			setControlVisible(View.GONE, View.GONE, View.VISIBLE, View.GONE, -1, -1, -1, -1);
			stopRecordingAndConvertFile(true);
			break;
		case UIGlobalDef.VIEW_ID.RECORD_MEDIA_RESUME:
			setControlVisible(-1, View.VISIBLE, View.GONE, View.VISIBLE, -1, -1, -1, -1);
			misStart = false;
			mWaveformView.onResumeRecording(misStart);
			break;
		case UIGlobalDef.VIEW_ID.RECORD_MEDIA_STOP:
			setControlVisible(View.VISIBLE, View.GONE, View.GONE, View.GONE, View.GONE, View.VISIBLE, View.GONE,View.VISIBLE);
			stopRecordingAndConvertFile(false);
			break;
		case UIGlobalDef.VIEW_ID.MEDIA_PREVIEW:
			Intent intentSound = new Intent(Intent.ACTION_VIEW);
			File audioFile = new File(mWaveformView.getFilePath());
			intentSound.setDataAndType(Uri.fromFile(audioFile), "audio/*");
			startActivity(intentSound);
			break;
		default:
			break;
		}
	}

	/**
	 * 停止录音并转换
	 */
	private void stopRecordingAndConvertFile(final boolean isPause) {
		new ProgressDialogHelper(mContext).showProgressDialog("", MediaConst.MSG_LOADING, new ProgressCallBack() {
			@Override
			public void action() {
				mWaveformView.stopRecordingAndConvertFile(isPause);
				mHandler.sendEmptyMessage(INT_STOP_UPDATE_VIEW);
			}
		});
	}

	@Override
	public void onBackPressed() {
		mWaveformView.stop();
		finish();
	}

	private View getContentCameraView(Context context) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		mvContent = new RelativeLayout(context);
		mvContent.setBackgroundColor(Color.BLACK);
		mWaveformView = new WaveformView(mContext);
		RelativeLayout.LayoutParams params = ActivityStyle.getContentCaneraLayoutParams();
        params.topMargin = mNavigationBarHeight;
        params.bottomMargin = mStatusBarHeight;
        mWaveformView.setLayoutParams(params);
		
		// 自定义波特
		mvContent.addView(mWaveformView);
		
		// Top
		HeaderView llTop = new HeaderView(context);
		RelativeLayout.LayoutParams llTopLayoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (int) (mfBaseDimen / 4 * 3));
		llTopLayoutParams.setMargins(0, ((int)MResource.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, displayMetrics)), 0, 0);
		llTop.setOrientation(LinearLayout.HORIZONTAL);
		llTop.setLayoutParams(llTopLayoutParams);
		mvContent.addView(llTop);
		
		mtvTime = new TextView(mContext);
		mtvTime.setTextColor(Color.WHITE);
		mtvTime.setTextSize(((int)MResource.applyDimension(TypedValue.COMPLEX_UNIT_SP, 6, displayMetrics)));
		mtvTime.setEms(3);
		mtvTime.setGravity(Gravity.CENTER);
		mtvTime.setVisibility(View.GONE);

		mtvTime.setBackgroundColor(Color.argb(148, 148, 148, 148));
		RelativeLayout.LayoutParams lTVTimeParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lTVTimeParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
		lTVTimeParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		lTVTimeParams.bottomMargin = mStatusBarHeight;
		mtvTime.setLayoutParams(lTVTimeParams);
		mvContent.addView(mtvTime);
		
		// Bottom
		LinearLayout llBottom = new FooterView(context);
		RelativeLayout.LayoutParams llBottomLayoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (int) (mfBaseDimen));
		llBottomLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
		llBottomLayoutParams.setMargins(0, 0, 0, ((int)MResource.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, displayMetrics)));
		llBottom.setOrientation(LinearLayout.HORIZONTAL);
		llBottom.setGravity(Gravity.CENTER_VERTICAL);
		mvContent.addView(llBottom, llBottomLayoutParams);
		
		mivCancel = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.CANCEL);
		mvContent.findViewById(UIGlobalDef.VIEW_ID.CAMERA_FACING).setVisibility(View.GONE);;
		mvContent.findViewById(UIGlobalDef.VIEW_ID.PIXELS).setVisibility(View.GONE);
		mvContent.findViewById(UIGlobalDef.VIEW_ID.CAMERA_FLASH).setVisibility(View.GONE);;
		mivOk = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.OK);

		mivStart = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.RECORD_MEDIA_START);
		mivPause = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.RECORD_MEDIA_PAUSE);
		mivResume = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.RECORD_MEDIA_RESUME);
		mivStop = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.RECORD_MEDIA_STOP);
		mivPreviewSound = (ImageView) mvContent.findViewById(UIGlobalDef.VIEW_ID.MEDIA_PREVIEW);
		mrprbTime = (RoundProgressBar) mvContent.findViewById(UIGlobalDef.VIEW_ID.ROUND_PROGRESS_BAR);
		
		mivCancel.setOnClickListener(this);
		mivOk.setOnClickListener(this);
		
		mivStart.setOnClickListener(this);
		mivPause.setOnClickListener(this);
		mivResume.setOnClickListener(this);
		mivStop.setOnClickListener(this);
		mivPreviewSound.setOnClickListener(this);
		mWaveformView.setAudioStater(this);
		return mvContent;
	}
	
	 /**
     * 启动任务计时
     */
	private void startTimerTask(boolean isStart, long time) {
		try {
			if (isStart) {
				mRecorderTime = 0;
			}
			// mThisTimes = Calendar.getInstance().getTimeInMillis();
			mThisTimes = time;
			// 创建定时器
			mTimer = new Timer();
			mTask = new TimerTask() {
				@Override
				public void run() {
					mRecorderTime = mRecorderTime + (Calendar.getInstance().getTimeInMillis() - mThisTimes);
					mHandler.sendEmptyMessage(INT_UPDATE_TAKE_TIME);
				}
			};
			mTimer.schedule(mTask, 0, 1000); // 延时1000ms后执行，1000ms执行一次
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAudioStart(long time) {
		startTimerTask(misStart, time);

	}

	@Override
	public void onAudioStop(long time) {
		mThisTimes = time;
		cancelTimerTask();

	}
	
	/**
	 * 取消任务计时器
	 */
	private void cancelTimerTask() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
	}
	

	/**
	 * 设置控件Visible属性
	 * @param intStart 开始
	 * @param intPause 暂停
	 * @param intResume 唤醒
	 * @param intStop 停止
	 * @param intTime 录制时间
	 * @param intPreview 预览
	 * @param intProgress 进度
	 * @param intOk OK
	 */
	private void setControlVisible(int intStart, int intPause, int intResume, int intStop, 
			int intTime, int intPreview,int intProgress, int intOk){
		if(intStart >= 0){
			mivStart.setVisibility(intStart);
		}
		if(intPause >= 0){
			mivPause.setVisibility(intPause);
		}
		if(intResume >= 0){
			mivResume.setVisibility(intResume);
		}
		if(intStop >= 0){
			mivStop.setVisibility(intStop);
		}
		if(intTime >= 0){
			mtvTime.setVisibility(intTime);
		}
		if(intPreview >= 0){
			mivPreviewSound.setVisibility(intPreview);
		}
		if(intOk >= 0){
			mivOk.setVisibility(intOk);
		}
	}
	
}
